package com.example.shiro.controller;

import com.example.shiro.dto.UserInfoDto;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class ShiroController {

    @GetMapping("login")
    public String login(HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "index";
        }
        return "login";
    }

    @GetMapping("index")
    public String index() {
        return "index";
    }

    @GetMapping("unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }

    @PostMapping("login")
    public String login(UserInfoDto userInfoDto, HttpServletRequest httpServletRequest) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userInfoDto.getUsername(), userInfoDto.getPassword());
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            httpServletRequest.setAttribute("message", e.getMessage());
            return "login";
        } catch (IncorrectCredentialsException e) {
            httpServletRequest.setAttribute("message", e.getMessage());
            return "login";
        }
    }

    @GetMapping("dologout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
}